package com.naihe.anderson.sms.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.CHeckSessionAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.NhsmsSession;
import com.naihe.anderson.sms.manager.NhSmsMgr;
import com.naihe.anderson.sms.widgets.RoundedRectListView;
import com.naihe.anderson.sms.widgets.SystemAlertDialog;

public class SaveSmsActivity extends Activity implements OnClickListener, OnItemClickListener {

	public static final int FILE_SAVE_RESULT_CODE = 1;

	NhSmsApp nhSmsApp;
	NhSmsMgr nhSmsMgr;
	
	Button back_btn;
	Button change_btn;
//	Button save_btn;
//	Button saveback_btn;

	CHeckSessionAdapter adapter;
	ListView checkSessionListview;
	List<NhsmsSession> nhsmsSessions = new ArrayList<NhsmsSession>();
	
	public static final int MSG_WHAT_MENU_DEL_SESSION = 0;
	public static final int MSG_WHAT_MENU_DEL_SESSION_GO = 1;
	
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_MENU_DEL_SESSION_GO:
				toDelSessionList();
				break;
			case MSG_WHAT_MENU_DEL_SESSION://删除会话
				Message message = mHandler.obtainMessage();
				message.what = MSG_WHAT_MENU_DEL_SESSION_GO;
				new SystemAlertDialog(SaveSmsActivity.this, mHandler, 
						getResources().getString(R.string.menu_btn_text_menu_bottom), 
						getResources().getString(R.string.alert_del_content), 
						getResources().getString(R.string.cancel), 
						getResources().getString(R.string.ok), message).show();
				break;
			default:
				break;
			}
		}
	};
	
	private void toDelSessionList(){
		List<NhsmsSession> delSession = new ArrayList<NhsmsSession>();
		for(Map.Entry<NhsmsSession, Boolean> entityMap : adapter.getCheckIfMap().entrySet())   
		{   
			if(entityMap.getValue() && TextUtils.isEmpty(entityMap.getKey().getCipher())){
				nhsmsSessions.remove(entityMap.getKey());
				delSession.add(entityMap.getKey());
			}
		}
		adapter.clearCheckIfMap();
		adapter.notifyDataSetChanged();
		nhSmsMgr.deleteNhSessionList(delSession);
		currentOpterSize = 0;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.save_message_layout);

		nhSmsApp = (NhSmsApp) getApplication();
		nhSmsApp.setActivity(this);
		nhSmsMgr = nhSmsApp.getNhSmsMgr();
		
		initView();
	}

	private void initView() {
		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
		change_btn = (Button) findViewById(R.id.change_btn);
		change_btn.setOnClickListener(this);

		checkSessionListview = (ListView) findViewById(R.id.smsSession_list);
		nhsmsSessions.addAll(nhSmsApp.getNhSmsMgr().getNsSmsSessionList());
		adapter = new CHeckSessionAdapter(this, nhsmsSessions);
		checkSessionListview.setAdapter(adapter);
		checkSessionListview.setOnItemClickListener(this);
		
//		save_btn = (Button) findViewById(R.id.save_btn);
//		saveback_btn = (Button) findViewById(R.id.saveback_btn);
//		save_btn.setOnClickListener(this);
//		saveback_btn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.back_btn) {
			finishActivityThing();
		} else if(v.getId() == R.id.change_btn){
			if(currentOpterSize > 0){
				if(mPopupWindow == null)
					initPopupWindows();
				mPopupWindow.update();
				mPopupWindow.showAsDropDown(v);
			} else {
				Toast.makeText(SaveSmsActivity.this, R.string.menu_popup_no_check, Toast.LENGTH_SHORT).show();
			}
		}
//		else if (v.getId() == R.id.save_btn) {
//			Intent intent = new Intent(SaveSmsActivity.this, MyFileManager.class);  
//			intent.putExtra("type", "directory");
//            startActivityForResult(intent, FILE_SAVE_RESULT_CODE);
//		} else if (v.getId() == R.id.saveback_btn) {
//			Intent intent = new Intent(SaveSmsActivity.this, MyFileManager.class);  
//			intent.putExtra("type", "file");
//            startActivityForResult(intent, FILE_BACK_RESULT_CODE);
//		}
	}

	PopupWindow mPopupWindow = null;
	private void initPopupWindows(){
		String[] muenString = new String[]{"删除","保存"};
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.menu_popup, null);
        RoundedRectListView menuListView = (RoundedRectListView) popunwindwow.findViewById(R.id.menuListView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SaveSmsActivity.this, R.layout.simple_list_item, muenString);
        menuListView.setAdapter(adapter);
        menuListView.setOnItemClickListener(this);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());//点击窗口外消失  
        mPopupWindow.setOutsideTouchable(true);  
        mPopupWindow.setFocusable(true);
	}
	
	private void finishActivityThing() {
		nhSmsApp.setActivity(null);
		finish();
		System.gc();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishActivityThing();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bundle bundle = null;
		if(data == null || (bundle=data.getExtras())==null){
			return;
		}
		String filePath = bundle.getString("file");
		if (FILE_SAVE_RESULT_CODE == requestCode) {
			toSaveSessionList(filePath);
		}
	}
	
	private void toSaveSessionList(String filePath){
		filePath = filePath + "/" + "nhsms_" + new Date().getTime() + "_bak";
		List<Long> saveSession = new ArrayList<Long>();
		for(Map.Entry<NhsmsSession, Boolean> entityMap : adapter.getCheckIfMap().entrySet())   
		{   
			if(entityMap.getValue() && TextUtils.isEmpty(entityMap.getKey().getCipher())){
				saveSession.add(entityMap.getKey().getTid());
			}
		}
		adapter.clearCheckIfMap();
		adapter.notifyDataSetChanged();
		currentOpterSize = 0;
		nhSmsMgr.saveNhSessionList(saveSession, filePath);
	}

	private int currentOpterSize = 0;
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(parent.getAdapter().getClass().equals(CHeckSessionAdapter.class)){
			NhsmsSession session = ((CHeckSessionAdapter)parent.getAdapter()).getItem(position);
			
			if(!TextUtils.isEmpty(session.getCipher())){
				Toast.makeText(SaveSmsActivity.this, R.string.menu_popup_has_password, Toast.LENGTH_SHORT).show();
				return;
			}
			
			CheckBox widget_checkbox = (CheckBox) view.findViewById(R.id.widget_checkbox);
			boolean ischecked = widget_checkbox.isChecked();
			if(ischecked){
				currentOpterSize --;
			} else {
				currentOpterSize ++;
			}
			widget_checkbox.setChecked(!ischecked);
			
			adapter.setCheckIfMap(session, !ischecked);
		} else {
			@SuppressWarnings("unchecked")
			String opter = ((ArrayAdapter<String>)parent.getAdapter()).getItem(position);
			if(opter.equals("保存")){
				Intent intent = new Intent(SaveSmsActivity.this, MyFileManager.class);  
				intent.putExtra("type", "directory");
	            startActivityForResult(intent, FILE_SAVE_RESULT_CODE);
			} else if(opter.equals("删除")){
				mHandler.sendEmptyMessage(MSG_WHAT_MENU_DEL_SESSION);
			}
			mPopupWindow.dismiss();
		}
	}
}
